#!/usr/bin/perl 

#
#   Cookie Monster, to be used with flatter.
#
#    Change the Cookie's path, domain and expires to something applicable
#    to your situation. 
# 
#	See www.cpan.org's docs on the CGI module's cookie functions
#
###############GPL Notice to Follow###################################
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#######################################################################

use CGI qw(:standard); #use included modules to handle cookies
use CGI::Cookie;
use CGI::Carp qw(fatalsToBrowser);


%classcart = cookie('classbag');


&ParseForm();
&GetCwd();
&read_config();
$filename = $vars{semfile1}; #default value could be changed via input
#decide which flatfile to use via hidden field in form
if ($form{sem} eq "$vars{semcode1}") {$filename = $vars{semfile1}; $semester = "$vars{semtitle1}";}
if ($form{sem} eq "$vars{semcode2}") {$filename = $vars{semfile2}; $semester = "$vars{semtitle2}";}

$semforself = "$form{sem}";
$toggle = $form{action};
$keyfield = $form{data};

@fields = split(',',$vars{fields});
($vars{field1},$vars{field2},$vars{field3},$vars{field4},$vars{field5},$vars{field6},$vars{field7},$vars{field8},$vars{field9},$vars{field10} ) = @fields;


if(%classcart)     #if cookie is there
{


    if($toggle == '1')        # add to cart
    {
     $classcart{$keyfield}++;
    }
    if($toggle == '0')        # delete from cart
    {
     delete $classcart{$keyfield};
    }
    $yoda = new CGI::Cookie(-name => 'classbag',
                            -value => \%classcart,
#                            -path => '/',
#                            -domain => '.webserver.com',
                            -expires => '+2w',
                            );

}
else                     # cookie not there make one
{

$classcart{$keyfield}++;
$yoda = new CGI::Cookie(-name => 'classbag',
                        -value => \%classcart,
#                        -path => '/',
#                        -domain => '.webserver.com',
                        -expires => '+2w',
                        );

}


# # # # # # # # #
#Gather Data    #
# # # # # # # # #
open(BORG,"<$filename");
@db = <BORG>;           #throw file into array
close(BORG);

foreach $item (@db)   #gets rid of EOL characters
   {
           chomp($item);
           if($item ne "") { push(@newdb,$item); }
   }
@db = @newdb;

$found = scalar keys %classcart;


if($found)
{
  foreach $line (%classcart)
  {

    foreach $record (@db)
    {
    ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10) = split(/\,/,$record);
    	if ($vars{index} eq "1"){ $indexer=$f1;}
    	if ($vars{index} eq "2"){ $indexer=$f2;}
    	if ($vars{index} eq "3"){ $indexer=$f3;}
    	if ($vars{index} eq "4"){ $indexer=$f4;}
    	if ($vars{index} eq "5"){ $indexer=$f5;}
    	if ($vars{index} eq "6"){ $indexer=$f6;}
    	if ($vars{index} eq "7"){ $indexer=$f7;}
    	if ($vars{index} eq "8"){ $indexer=$f8;}
    	if ($vars{index} eq "9"){ $indexer=$f9;} 
    	if ($vars{index} eq "10"){$indexer=$f10;}

		if ($indexer == $line) { push(@matches,$record); }    
    }
  }
}


#################
#Build Output   #
#################
$fontsize = "<font size=\"-2\">"; #change these to change the fontsize of
$endfont = "</font>";             #the output
#$deleter = "<a href=\"http://wosc.wox.org/cgi-bin/cookie.pl?action=0&data=$section\">Delete</a>


print header(-cookie=>$yoda);
#print "content-type:text/html\n\n";
print ApplyTemplate("$vars{header}");
#print start_html('Class Cart');
print "<table cellspacing=\"3\" cellpadding=\"1\" align \"center width=\"673\"\">";
print "<tr><td colspan=\"12\"><center><h2>$semester</h2></center></td></tr>";
print "<tr><td colspan=\"12\">Classes Stored : $found </td></tr>";
print "<tr><td>$fontsize $vars{field1} $endfont</td><td>$fontsize $vars{field2} $endfont</td><td>$fontsize $vars{field3} $endfont</td><td>$fontsize $vars{field4} $endfont</td><td>$fontsize $vars{field5} $endfont</td><td>$fontsize $vars{field6} $endfont</td><td>$fontsize $vars{field7} $endfont</td><td>$fontsize $vars{field8} $endfont</td><td>$fontsize $vars{field9} $endfont</td><td>$fontsize $vars{field10} $endfont</td><td>$fontsize Remove Class $endfont</td></tr>";
print "<font size=\"-1\">";

    foreach $match(@matches)
    {
    ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10) = split(/\,/,$match);
    	if ($vars{index} eq "1"){ $indexer=$f1;}
    	if ($vars{index} eq "2"){ $indexer=$f2;}
    	if ($vars{index} eq "3"){ $indexer=$f3;}
    	if ($vars{index} eq "4"){ $indexer=$f4;}
    	if ($vars{index} eq "5"){ $indexer=$f5;}
    	if ($vars{index} eq "6"){ $indexer=$f6;}
    	if ($vars{index} eq "7"){ $indexer=$f7;}
    	if ($vars{index} eq "8"){ $indexer=$f8;}
    	if ($vars{index} eq "9"){ $indexer=$f9;} 
    	if ($vars{index} eq "10"){$indexer=$f10;}

    print  "<tr><td>$fontsize $f1 $endfont</td><td>$fontsize $f2 $endfont</td><td>$fontsize $f3 $endfont</td><td>$fontsize $f4 $endfont</td> $endfont<td>$fontsize $f5 $endfont</td><td>$fontsize $f6 $endfont</td><td>$fontsize $f7 $endfont</td><td>$fontsize $f8 $endfont</td><td>$fontsize $f9 $endfont</td><td>$fontsize $f10 $endfont</td><td><a href=\"$vars{cookieurl}?action=0&data=$indexer&sem=$semforself\">$fontsize Delete $endfont</a></td></tr>";
    }

print "</font>";
print "</tr><td><INPUT TYPE=\"button\" VALUE=\"  BACK  \" onClick=\"window.close()\"></td><td><input type=button name=print value=\"Print\" onClick=\"javascript:window.print()\"> </td></tr>";
print "</table>";
print ApplyTemplate("$vars{footer}");



#.....................................................
sub ApplyTemplate {
local(*FILE);         # filehandle
local($file);         # file path
local($HTML);         # HTML data

$file = $_[0] || die "Template : No template file specified\n";

open(FILE, "<$file") or die "Template : Couldn't open $file : $!\n";
while (<FILE>) { $HTML .= $_; }
close(FILE);

$HTML =~ s/\$(\w+)/${$1}/g;

return $HTML;
}

sub read_config {
	my $config_file;
	$vars{config} = "cf3.cfg";
	$config_file = $vars{base_dir} . $vars{config};
	my $key,$val;
	open(IN,$config_file) || die ("Can't open config file $config_file.");
	while(<IN>) {
		next if /^#/;
		chomp;
		($key,$val) = ( /([^=]+)=(.*)/ );
		$key = lc($key);
		$val =~ s|\[(\S+)\]|$vars{$1}|g;
		$val =~ s|\s*$||;
		$vars{$key} = $val;
		}
	close(IN);
}

sub GetCwd {
	if ($base_dir) { $vars{base_dir} = $base_dir; }
	return if $vars{base_dir};
	my $path =  $ENV{'PATH_TRANSLATED'} || $ENV{'SCRIPT_FILENAME'};
	unless ($path) {
		die ("Your server does not provide the PATH_TRANSLATED or SCRIPT_FILENAME environment variables.<br><br>Please see the installation documentation for how to set the \$base_dir variable manually.");
		exit(0);
		}
	$path =~ s|[^/\\]*$||;
	$vars{base_dir} = $path;
	}
	
sub ParseForm {
$query = $ENV{QUERY_STRING};
if($query =~ /\w+/)
{
    @pairs = split ('&',$query); #check for url sumbitted info
}                                # like cgi-bin/coursefinder.pl?time=pm&sem=fall
else 
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
}

foreach $pair (@pairs)
{
   ($name, $value) = split(/=/, $pair);
   $value =~ tr/+/ /;
   $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
   $value =~ s/\n//g;
   $value =~ s/\r/<BR>/g;
   $form{$name} = $value;
}
}
